package com.phamkhanh.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/logout.html")
public class LogoutController {
	
	private Logger logger = Logger.getLogger(LogoutController.class);
	
	@RequestMapping(method = RequestMethod.GET)
	public String logoutAction(HttpServletRequest request, HttpServletResponse response){
		logger.info("Bắt đầu xử lí logout");
		if(request.getSession().getAttribute("user") != null){
			logger.info("- Xóa session");
			request.getSession().invalidate();
		}
		
		Cookie cookie = this.getCookie("uid", request);
		if(cookie != null){
			logger.info("- Xóa cookie");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
		
		logger.info("- Chuyển về trang index.html, logout thành công.");
		return "redirect:index.html";
	}
	
	
	
	
	
	/**
	 * Method get Cookie object by name, if not exist Cookie corresponding to name , return null
	 * @param name 
	 * 				name of Cookie want to get
	 * @param request
	 * 				HttpServletRequest contains Cookies
	 */
	public Cookie getCookie(String name, HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for(Cookie cookie : cookies){
				if(cookie.getName().equals(name)) return cookie;
			}
		}
		return null;
	}
}
